package io.renren.modules.oa.controller;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.domain.model.v20180129.QueryDomainListRequest;
import com.aliyuncs.domain.model.v20180129.QueryDomainListResponse;
import com.aliyuncs.ecs.model.v20140526.DescribeInstancesRequest;
import com.aliyuncs.ecs.model.v20140526.DescribeInstancesResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.rds.model.v20140815.DescribeDBInstanceAttributeRequest;
import com.aliyuncs.rds.model.v20140815.DescribeDBInstanceAttributeResponse;

import io.renren.common.utils.DateUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.oa.entity.EscInstancesEntity;
import io.renren.modules.oa.entity.OaPlanEmployeeEntity;
import io.renren.modules.oa.redis.DingtalkRedis;
import io.renren.modules.oa.service.EscInstancesService;
import io.renren.modules.sys.shiro.ShiroUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;



/**
 * 云服务器ECS
 *
 * @author ziye
 * @email 524748907@qq.com
 * @date 2019-01-24 10:22:21
 */
@RestController
@RequestMapping("oa/escinstances")
public class EscInstancesController {
    @Autowired
    private EscInstancesService escInstancesService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("oa:escinstances:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = escInstancesService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("oa:escinstances:info")
    public R info(@PathVariable("id") Integer id){
        EscInstancesEntity escInstances = escInstancesService.selectById(id);

        return R.ok().put("escInstances", escInstances);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("oa:escinstances:save")
    public R save(@RequestBody EscInstancesEntity escInstances){
    	 if(escInstances.getType() == 3){	//域名
    		 return createDomainInstance(escInstances);
    	 }else if(escInstances.getType() == 2){	//数据库
    		return createDescribeDBInstance(escInstances); 
    	 }else{
    		 return createSnapshot(escInstances);
    	 }
    	 
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("oa:escinstances:update")
    public R update(@RequestBody EscInstancesEntity escInstances){
        ValidatorUtils.validateEntity(escInstances);
        if(escInstances.getType() == 3){	//域名
        	return createDomainInstance(escInstances);
        }else if(escInstances.getType() == 2){	//数据库
    		return createDescribeDBInstance(escInstances); 
        }else{
        	return createSnapshot(escInstances);
        }
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("oa:escinstances:delete")
    public R delete(@RequestBody Integer[] ids){
        escInstancesService.deleteBatchIds(Arrays.asList(ids));

        return R.ok();
    }
    
    @RequestMapping("/updateExpiredTime")
    public R updateExpiredTime(Long id){
    	System.out.println(id);
    	EscInstancesEntity escInstances = escInstancesService.selectById(id);
        if(escInstances.getType() == 3){	//域名
        	return createDomainInstance(escInstances);
        }else if(escInstances.getType() == 2){	//数据库
    		return createDescribeDBInstance(escInstances); 
        }else{
        	return createSnapshot(escInstances);
        }
    }
    public R createDomainInstance(EscInstancesEntity escInstance) {
    	
    	DefaultProfile profile = DefaultProfile.getProfile(escInstance.getRegionId(), escInstance.getAccessKeyId(), escInstance.getAccessKeySecret());
    	IAcsClient client = new DefaultAcsClient(profile);
    	
    	QueryDomainListRequest request = new QueryDomainListRequest();
    	request.setActionName("QueryDomainList");
    	request.setPageNum(0);
    	request.setPageSize(50);
    	request.setDomainName(escInstance.getInstanceId());
    	try {
    		QueryDomainListResponse response = client.getAcsResponse(request);
    		JSONArray arr = JSONArray.fromObject(response.getData());  
    		if(arr != null && arr.size() > 0){
    			logInfo(arr.toString());
    			JSONObject result = arr.getJSONObject(0);	//阿里云结果
    			escInstance.setInstanceName(result.getString("domainName"));
    			escInstance.setRegionId("");
    			escInstance.setCreationTime(DateUtils.stringToDate(result.getString("registrationDate"), DateUtils.DATE_TIME_PATTERN));
    			escInstance.setExpiredTime( DateUtils.stringToDate(result.getString("expirationDate"), DateUtils.DATE_TIME_PATTERN));
    			escInstance.setPublicIpAddresse(result.getString("domainName"));
    			//escInstance.setInnerIpAddresse(result.getJSONObject("vpcAttributes").getJSONArray("privateIpAddress").getString(0));
    			System.out.println(result.getString("domainName"));
    			if(escInstance.getId() != null && escInstance.getId() > 0){
    				escInstancesService.insertOrUpdate(escInstance);//全部更新
    			}else{
    				escInstancesService.insert(escInstance)	;
    			}
    			
    			return R.ok();
    		}else{
    			return R.error("该账号暂无无云数据库RDS");
    		}
//        	System.out.println(arr.toString());
//        	return escInstance;
    	} catch (ServerException e) {
    		logInfo(String.format("失败. 阿里云配置错误, 错误代码: %s",
    				e.getErrCode()));
    		return R.error(String.format("失败. 阿里云配置错误, 错误代码: %s",
    				e.getErrCode()));
    	} catch (ClientException e) {
    		logInfo(String.format("失败. 业务错误. 错误代码: %s, 请求编号: %s",
    				e.getErrCode(), e.getRequestId()));
    		return R.error(String.format("失败. 业务错误. 错误代码: %s, 请求编号: %s",
    				e.getErrCode(), e.getRequestId()));
    	}
    	
    }
    public R createDescribeDBInstance(EscInstancesEntity escInstance) {
    	
        DefaultProfile profile = DefaultProfile.getProfile(escInstance.getRegionId(), escInstance.getAccessKeyId(), escInstance.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);
        
        DescribeDBInstanceAttributeRequest request = new DescribeDBInstanceAttributeRequest();
        request.setActionName("DescribeDBInstanceAttribute");
        request.setDBInstanceId(escInstance.getInstanceId());
        try {
        	DescribeDBInstanceAttributeResponse response = client.getAcsResponse(request);
        	JSONArray arr = JSONArray.fromObject(response.getItems());  
        	if(arr != null && arr.size() > 0){
        		logInfo(arr.toString());
        		JSONObject result = arr.getJSONObject(0);	//阿里云结果
        		escInstance.setInstanceName(result.getString("DBInstanceDescription"));
        		escInstance.setRegionId(result.getString("regionId"));
        		escInstance.setCreationTime( UTCToCST(result.getString("creationTime"),"yyyy-MM-dd'T'HH:mm:ssXXX"));
        		escInstance.setExpiredTime( UTCToCST(result.getString("expireTime"),"yyyy-MM-dd'T'HH:mm:ssXXX"));
        		escInstance.setPublicIpAddresse(result.getString("connectionString"));
        		//escInstance.setInnerIpAddresse(result.getJSONObject("vpcAttributes").getJSONArray("privateIpAddress").getString(0));
        		System.out.println(result.getString("connectionString"));
        		if(escInstance.getId() != null && escInstance.getId() > 0){
        			escInstancesService.insertOrUpdate(escInstance);//全部更新
        		}else{
        			escInstancesService.insert(escInstance)	;
        		}
        		
        		return R.ok();
        	}else{
        		return R.error("该账号暂无无云数据库RDS");
        	}
//        	System.out.println(arr.toString());
//        	return escInstance;
        } catch (ServerException e) {
            logInfo(String.format("失败. 阿里云配置错误, 错误代码: %s",
                e.getErrCode()));
            return R.error(String.format("失败. 阿里云配置错误, 错误代码: %s",
                    e.getErrCode()));
        } catch (ClientException e) {
            logInfo(String.format("失败. 业务错误. 错误代码: %s, 请求编号: %s",
                e.getErrCode(), e.getRequestId()));
           return R.error(String.format("失败. 业务错误. 错误代码: %s, 请求编号: %s",
                   e.getErrCode(), e.getRequestId()));
        }
        
    }
    
    
    //查看地域
    //https://help.aliyun.com/document_detail/40654.html?spm=a2c4g.11186623.2.11.751135bdlMdcpQ
    public R createSnapshot(EscInstancesEntity escInstance) {
    	
        DefaultProfile profile = DefaultProfile.getProfile(escInstance.getRegionId(), escInstance.getAccessKeyId(), escInstance.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);
        
        DescribeInstancesRequest request = new DescribeInstancesRequest();
        request.setActionName("DescribeInstances");
        request.setRegionId(escInstance.getRegionId());
        request.setInstanceIds("[\""+escInstance.getInstanceId()+"\"]");
        try {
        	DescribeInstancesResponse response = client.getAcsResponse(request);
        	JSONArray arr = JSONArray.fromObject(response.getInstances());  
        	if(arr != null && arr.size() > 0){
        		logInfo(arr.toString());
        		JSONObject result = arr.getJSONObject(0);	//阿里云结果
        		escInstance.setInstanceName(result.getString("instanceName"));
        		escInstance.setCreationTime( UTCToCST(result.getString("creationTime"),"yyyy-MM-dd'T'HH:mmXXX"));
        		escInstance.setExpiredTime( UTCToCST(result.getString("expiredTime"),"yyyy-MM-dd'T'HH:mmXXX"));
        		escInstance.setPublicIpAddresse(result.getJSONArray("publicIpAddress").getString(0));
        		//escInstance.setInnerIpAddresse(result.getJSONObject("vpcAttributes").getJSONArray("privateIpAddress").getString(0));
        		System.out.println(result.get("publicIpAddress"));
        		if(escInstance.getId() != null && escInstance.getId() > 0){
        			escInstancesService.insertOrUpdate(escInstance);//全部更新
        		}else{
        			escInstancesService.insert(escInstance)	;
        		}
        		
        		return R.ok();
        	}else{
        		return R.error("该账号下无服务器");
        	}
//        	System.out.println(arr.toString());
//        	return escInstance;
        } catch (ServerException e) {
            logInfo(String.format("失败. 阿里云配置错误, 错误代码: %s",
                e.getErrCode()));
            return R.error(String.format("失败. 阿里云配置错误, 错误代码: %s",
                    e.getErrCode()));
        } catch (ClientException e) {
            logInfo(String.format("失败. 业务错误. 错误代码: %s, 请求编号: %s",
                e.getErrCode(), e.getRequestId()));
           return R.error(String.format("失败. 业务错误. 错误代码: %s, 请求编号: %s",
                   e.getErrCode(), e.getRequestId()));
        }
        
    }
    
    /**
     * SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmXXX");
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		try {
				//   2019-01-05T01:17Z
		      Date date = sdf1.parse("2019-01-05T01:17Z");//拿到Date对象
		      String str = sdf2.format(date);//输出格式：2017-01-22 09:28:33
		      System.out.println(str);
		  } catch (Exception e) {
		      e.printStackTrace();
		  }
     * @param UTCStr
     * @return
     */
    public static Date UTCToCST(String UTCStr,String format) {
    	try {
    		Date date = null;
	        SimpleDateFormat sdf = new SimpleDateFormat(format);
	        date = sdf.parse(UTCStr);
	        System.out.println("UTC时间: " + date);
	        return date;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
    }
    
    private static void logInfo(String message) {
       System.out.println(message);
    }
    

}
